#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include<functional>
#include "Log.hpp"
#include "InetAddr.hpp"

enum 
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

const static int defaultsockfd  = -1;
const uint16_t defaultport = 8888;

using hander_message_t = std::function<void (int,const std::string,const InetAddr)>;

class UdpServer
{
public:
    UdpServer(uint16_t port,hander_message_t hander_message):_sockfd(defaultsockfd),_port(port),_isrunning(false),_hander_message(hander_message)
    {
    }

    void InitServer()
    {
        // 1. 创建udp socket --必须要做的
        //2. _sockfd 是全双工的，通过sockfd就能体现出来
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);
        //2.0 填充sockaddr_in 结构
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); 
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = 0;
        local.sin_addr.s_addr = INADDR_ANY;
        // 2. bind sockfd ip和网络信息(IP(?) + port);
        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");

    }

    void Start()//所有的服务器，本质是解决的是输入输出的问题！不想让网络模块和业务模块强耦合
    {
        //一直运行，直到管理者不想运行了
        _isrunning = true;
        while(true)
        {
            char message[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd,message,sizeof(message)-1,0,(struct sockaddr*)&peer,&len);//谁给我发的
            if(n > 0)
            {
                message[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG,"get a message from [%s : %d] : %s\n",addr.IP().c_str(),addr.PORT(),message);

                _hander_message(_sockfd,message,addr);

                //将我的请求回调出去，在外部处理
                // bool ok;
                // std::string response = _func(request,ok);

                // sendto(_sockfd,response.c_str(),response.size(),0,(struct sockaddr *)&peer,len);
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    // std::string _ip;
    uint16_t _port;
    bool _isrunning;

    //给服务器设定回调，用来让上层 进行注册业务的处理方法
    hander_message_t _hander_message;
};